package etc.server.csp;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

@Slf4j
public class CspClient {
    static Socket socket = null;
    static OutputStream os = null;
    static InputStream is = null;

    /**
     * 发送心跳包
     */
    public static byte[] socket(String reqcontent, String ip, int port) {
        long startTime = System.currentTimeMillis();
        try {
            if (socket == null || socket.isClosed()) {
                //socket = new Socket("127.0.0.1", 6001); // 连接socket
                socket = new Socket(ip, port);
                os = socket.getOutputStream();
            }
            try {
                log.info("client==send==forward====================================================");
                os.write(reqcontent.getBytes("GBK"));
                os.flush();
//                    Thread.sleep(10 * 1000);// 等待3秒
                while (true) {
                    is = socket.getInputStream();
                    int size = is.available();
                    if (size <= 0) {
                        if ((System.currentTimeMillis() - startTime) > 6 * 10 * 1000) {
                            // 如果超过30秒没有收到服务器发回来的信息，说明socket连接可能已经被远程服务器关闭
                            // 这时候可以关闭socket连接
                            socket.close();
                            startTime = System.currentTimeMillis();
                        }
                        continue;
                    } else {
                        startTime = System.currentTimeMillis();
                    }
                    byte[] resp = new byte[size];
                    is.read(resp);
                    log.info("client==receive==forward====================================================");
                    return resp;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void close() {
        if (socket != null || !socket.isClosed()) {
            //socket = new Socket("127.0.0.1", 6001); // 连接socket
            try {
                socket.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }


}
